package com.ts.notice.job;

import com.ts.common.core.corethreadPool.ExecutorUtils;
import com.ts.notice.constants.RedisKey;
import com.ts.notice.dto.SMSDto;
import com.ts.notice.utils.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Set;

@EnableScheduling
@Slf4j
@Component
public class SMSJob {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SMSUtils smsUtils;

//    @Scheduled(cron = "0/20 * * * * *")
    public void reSendSms(){

        ExecutorUtils.getThreadPoll().submit(()->{

            //从reids中查询失败的短信
            Set members = redisTemplate.opsForSet().members(RedisKey.SEND_SMS_ERROR_KEY);

            if (members.isEmpty() || members.size() == 0){
                log.debug("本次任务没有要发送的短信，执行结束");
                return;
            }

            //遍历循环发送失败的短信
            Iterator iterator = members.iterator();
            while (iterator.hasNext()){
                SMSDto smsDto = (SMSDto) iterator.next();

                //查询短信发送的状态
                Boolean flag = smsUtils.query(smsDto.getPhone(), smsDto.getTaskId());
                if (!flag){
                    SMSDto newDto = new SMSDto();
                    newDto.setPhone(smsDto.getPhone());
                    newDto.setCode(smsDto.getCode());

//                smsUtils.send(newDto);
                }
                //这个短信以发送成功，需要删除
                redisTemplate.opsForSet().remove(RedisKey.SEND_SMS_ERROR_KEY,smsDto);

            }
        });

    }

}
